package com.wuercloud.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitManagementTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wuercloud.dao.QueuesDao;
import com.wuercloud.entity.QueuesEntity;
import com.wuercloud.service.QueuesService;

@Service("queuesService")
public class QueuesServiceImpl implements QueuesService {
	private Logger logger = LoggerFactory.getLogger(QueuesServiceImpl.class);
	@Autowired
	private QueuesDao queuesDao;
	@Autowired
	private RabbitManagementTemplate rabbitManagementTemplate;
	@Value("${rabbitmq-VirtualHost}")
	private String vhost;

	@Override
	public QueuesEntity queryObject(Integer queuesId) {
		return queuesDao.queryObject(queuesId);
	}

	@Override
	public List<QueuesEntity> queryList(Map<String, Object> map) {
		return queuesDao.queryList(map);
	}

	@Override
	public int queryTotal(Map<String, Object> map) {
		return queuesDao.queryTotal(map);
	}

	@Override
	public void save(QueuesEntity queues) {

		// 队列消息的过期时间
		Map<String, Object> arguments = new HashMap<>();
		arguments.put("x-message-ttl", queues.getDietime());
		logger.info("队列过期时间是：{}", queues.getDietime());
		// 队列参数
		Queue queue = new Queue(queues.getQueuesName(), queues.getDurability(), queues.getExclusive(),
				queues.getAutodelete(), arguments);
		// 创建队列
		rabbitManagementTemplate.addQueue(vhost, queue);
		logger.info("{}队列创建成功", queues.getQueuesName());

		queuesDao.save(queues);
	}

	@Override
	public void update(QueuesEntity queues) {
		queuesDao.update(queues);
	}

	@Override
	public void delete(Integer queuesId) {
		queuesDao.delete(queuesId);
	}

	@Override
	public void deleteBatch(Integer[] queuesIds) {
		Arrays.asList(queuesIds).stream().forEach(queuesId -> {
			rabbitManagementTemplate.deleteQueue(vhost, new Queue(queuesDao.queryObject(queuesId).getQueuesName()));
		});
		logger.info("＝＝＝＝＝列队删除成功＝＝＝＝＝＝");

		queuesDao.deleteBatch(queuesIds);
	}
}
